<template>
    <div style="height:100%">
      <!-- 图片上传组件辅助 -->
      <!-- <el-upload :action="uploadImgUrl" ref="uploadFileImage" :data="imgCol" :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess" :on-error="uploadError" name="file" :show-file-list="false" :headers="headers"
        style="display: none" /> -->
      <el-upload action="" ref="uploadFileImage" :data="imgCol" :auto-upload="false"
        :on-change="(file) => { handleUploadSuccess(file, 'image') }" :on-remove="handleRemove" accept=".png,.jpg,.jpeg"
        style="display: none" name="file" :show-file-list="false" />
      <!--视频上传组件辅助 -->
      <!-- <el-upload :action="uploadImgUrl" ref="uploadFileVideo" :data="imgColVideo" :before-upload="handleBeforeUploadVideo"
        :on-success="handleUploadSuccessVideo" :on-error="handleUploadErrorVideo" name="file" :show-file-list="false"
        :headers="headers" style="display: none" /> -->
      <el-upload action="" ref="uploadFileVideo" :data="imgColVideo" :auto-upload="false"
        :on-change="(file) => { handleUploadSuccess(file, 'video') }" :on-remove="handleRemove"
        accept=".mp4, .avi, .mpg, .rmvb" style="display: none" name="file" :show-file-list="false" />
      <!-- 富文本组件 -->
      <!-- <quill-editor :id="randomString(3)" class="editor" v-model="content" :ref="toref" :options="editorOption"
            @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"></quill-editor> -->
      <quill-editor class="editor" v-model="content" ref="toref" :options="editorOption" @blur="onEditorBlur($event)"
        @focus="onEditorFocus($event)" @change="onEditorChange($event)" v-loading="quillUpdateImg" :disabled="disabled">
      </quill-editor>
    </div>
  </template>
  
  <script>
  
  import $baseUrl from '@/utils/baseURL';
  import fileApi from '@/api/file';
  import ImageResize from 'quill-image-resize-module'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'
  Quill.register('modules/imageResize', ImageResize)
  import { quillEditor } from 'vue-quill-editor'
  
  // 自定义字体大小
  let Size = Quill.import('attributors/style/size')
  Size.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px']
  Quill.register(Size, true)
  
  // 自定义字体类型
  var fonts = ['SimSun', 'SimHei', 'Microsoft-YaHei', 'KaiTi', 'FangSong', 'Arial', 'Times-New-Roman', 'sans-serif']
  var Font = Quill.import('formats/font')
  Font.whitelist = fonts // 将字体加入到白名单
  Quill.register(Font, true)
  
  //视频标签插入（样式保持宽度100%）
  import video from '../../utils/video'
  Quill.register(video, true)
  export default {
    props: {
      /* 编辑器的内容 */
      value: {
        type: String
      },
      /* 图片大小 */
      maxSize: {
        type: Number,
        default: 4000 //kb
      },
      quillIndex: {
        type: Number,
        default: 0
      },
      toref: {
        type: String,
        default: "quillEditor"
      },
      disabled: {
        type: Boolean,
        default: false
      },
    },
    components: { quillEditor },
    data() {
      return {
        content: this.value,
        editorOption: {
          placeholder: '输入文本...',
          theme: 'snow', //主题
          modules: {
            imageResize: {   //添加图片拖拽上传，自定义大小（下面会详细介绍安装方法）
              displayStyles: {   //添加
                backgroundColor: 'black',
                border: 'none',
                color: 'white'
              },
              modules: ['Resize', 'DisplaySize', 'Toolbar']   //添加
            },
            toolbar: {
              container: [
                // [{ 'font':fonts }],
                ['bold', 'italic', 'underline', 'strike'],    //加粗，斜体，下划线，删除线
                ['blockquote', 'code-block'],     //引用，代码块
                [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
                [{ 'list': 'ordered' }, { 'list': 'bullet' }],     //列表
                [{ 'script': 'sub' }, { 'script': 'super' }],   // 上下标
                [{ 'indent': '-1' }, { 'indent': '+1' }],     // 缩进
                [{ 'direction': 'rtl' }],             // 文本方向
                // [{ 'size':Size }], // 字体大小，false设置自定义大小
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],     //几级标题
                [{ 'color': [] }, { 'background': [blur()] }],     // 字体颜色，字体背景颜色
                // [{ 'font': fonts }],     //字体
                [{ 'align': [] }],    //对齐方式
                ['clean'],    //清除字体样式
                ['image', 'video']    //上传图片、上传视频
              ],
              handlers: {
                video: this.handelVideo,
                image: this.handelImage,
              }
            }
          }
        },
        quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
        imgCol: {
          //图片传递的参数
        },
        imgColVideo: {
          //视频传递的参数
        },
        uploadImgUrl: '', // 上传的图片服务器地址
        headers: {
          //登录成功后的token字段，没有可以不用传
        },
  
      };
    },
    watch: {
      value: function () {
        this.content = this.value;
      }
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file)
      },
      handleChangeUpload(file, fileList) {
        console.log(file)
      },
      onEditorBlur() {
        //失去焦点事件
      },
      onEditorFocus() {
        //获得焦点事件
      },
      onEditorChange() {
        //内容改变事件
        this.$emit("update", this.content);
      },
      handelVideo() {
        //自定义上传视频事件
  
        this.uploadType = "video";
        this.$nextTick(() => {
          this.$refs.uploadFileVideo.$children[0].$refs.input.click();
        });
      },
      handelImage() {
        this.uploadType = "image";
        this.$nextTick(() => {
          this.$refs.uploadFileImage.$children[0].$refs.input.click();
        });
      },
      // 上传前校检格式和大小
      handleBeforeUpload(file) {
        this.quillUpdateImg = true
        // console.log(file)
        if (this.uploadType === "image") {
          let regArr = [".gif", ".jpg", ".jpeg", ".png"];
          let lastName = file.name.slice(file.name.indexOf("."));
          if (regArr.indexOf(lastName) == -1) {
            this.$message.error(`仅支持.gif/.jpg/.jpeg/.png格式!`);
            this.quillUpdateImg = false
            return false;
          }
        }
      },
      async getFileId(file) {
        let fileId = null
        let fd = new FormData();
        fd.append("file", file.raw)
        console.log(fd, 'fd')
        await fileApi.upload(fd).then(res => {
          fileId = res.data
        }).catch(err => {
          console.log('出错了', err)
        });
        return fileId
      },
      async handleUploadSuccess(file, flag) {
        console.log(file)
        // // 获取富文本组件实例
        let quill = this.$refs.toref.quill
        // 如果上传成功myQuillEditor
        let fileUrl = $baseUrl.fileServiceUrl + 'portalWebsite/files/download?fileId=' + await this.getFileId(file);
        // 获取光标所在位置
        let length = quill.getSelection().index;
        if (flag == 'image') {
          // 插入图片  res.info为服务器返回的图片地址
          quill.insertEmbed(length, 'image', fileUrl)
        } else if (flag == 'video') {
          quill.insertEmbed(length, 'video', {
            url: fileUrl,
            controls: 'controls',
            width: '100%',
            height: 'auto'
          })
        }
        // 调整光标到最后
        quill.setSelection(length + 1)
        this.quillUpdateImg = false
      },
      uploadError() {
        if (this.uploadType != "image") {
          this.$message.error("图片插入失败!");
        }
      },
      // 上传前校检格式和大小
      handleBeforeUploadVideo(file) {
        this.quillUpdateImg = true
        console.log(file)
        if (this.uploadType === "video") {
          let acceptType = [
            "mp4",
            "avi",
            "mpg",
            "rmvb",
          ];
          let isVideo = null;
          acceptType.some((d) => {
            if (file.type.includes(d)) {
              isVideo = true;
            }
          });
          if (!isVideo) {
            this.$message.error(
              "上传视频只能是  mp4, avi, mpg, rmvb格式!"
            );
            this.quillUpdateImg = false
            return false;
          }
          return true;
        }
      },
      handleUploadSuccessVideo(res, file) {
        // console.log(res.data.fileUrl)
        // // 获取富文本组件实例
        let quill = this.$refs.toref.quill
        // 如果上传成功
        if (res.status == '0') {
          // 获取光标所在位置
          // let length = quill.getSelection().index;
          if (this.uploadType === "video") {
            let length = quill.getSelection().index;
            // 插入图片res.url为服务器返回的地址
            quill.insertEmbed(length, 'video', {
              url: res.data.fileUrl,
              controls: 'controls',
              width: '100%',
              height: 'auto'
            })
          }
          // // 调整光标到最后
          quill.setSelection(length + 1);
          this.$message.success(res.data.msg)
        } else {
          this.$message.error("插入失败");
        }
        this.quillUpdateImg = false
      },
      handleUploadErrorVideo() {
        if (this.uploadType != "video") {
          this.$message.error("视频插入失败!");
        }
      },
    }
  };
  </script>
  
  <style lang="scss" scoped>
    ::v-deep .ql-container {
      min-height: 200px;
    }
  </style>
  